import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/api/calendar.dart';
import 'package:geomancy/models/auspicious_time_list_model.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:geomancy/tools/utils.dart';
import 'package:geomancy/widgets/common_header.dart';
import 'package:geomancy/widgets/common_shadow_text.dart';
import 'package:geomancy/widgets/common_text.dart';
import 'package:geomancy/widgets/common_title.dart';

class GoodOccasionPage extends StatefulWidget {
  final DateTime date;
  const GoodOccasionPage({super.key, required this.date});

  @override
  State<GoodOccasionPage> createState() => _GoodOccasionPageState();
}

class _GoodOccasionPageState extends State<GoodOccasionPage> {
  late String dateShowText;
  Map<int, HourlyHoroscope>? dataMap;

  @override
  void initState() {
    super.initState();
    dateShowText = '${widget.date.year}年${widget.date.month}月${widget.date.day}日';
    chooseAnAuspiciousTime();
  }

  Future chooseAnAuspiciousTime() async {
    final result = await CalendarAPI.chooseAnAuspiciousTime(context, Utils.getFormatDate(dateTime: DateTime.now()));
    setState(() {
      dataMap = result?.html;
    });
  }

  Map<String, dynamic> getTimePeriod(int index) {
    // 十二时辰的名称和对应的时间区间，时间分开为开始时间和结束时间
    List<Map<String, dynamic>> timePeriods = [
      {'name': '子时', 'start': '23:00', 'end': '00:59'},
      {'name': '丑时', 'start': '01:00', 'end': '02:59'},
      {'name': '寅时', 'start': '03:00', 'end': '04:59'},
      {'name': '卯时', 'start': '05:00', 'end': '06:59'},
      {'name': '辰时', 'start': '07:00', 'end': '08:59'},
      {'name': '巳时', 'start': '09:00', 'end': '10:59'},
      {'name': '午时', 'start': '11:00', 'end': '12:59'},
      {'name': '未时', 'start': '13:00', 'end': '14:59'},
      {'name': '申时', 'start': '15:00', 'end': '16:59'},
      {'name': '酉时', 'start': '17:00', 'end': '18:59'},
      {'name': '戌时', 'start': '19:00', 'end': '20:59'},
      {'name': '亥时', 'start': '21:00', 'end': '22:59'}
    ];

    // 确保索引在 0-11 范围内
    if (index >= 0 && index < timePeriods.length) {
      return {
        'name': timePeriods[index]['name']!,
        'start': timePeriods[index]['start']!,
        'end': timePeriods[index]['end']!
      };
    } else {
      throw ArgumentError('Index must be between 0 and 11');
    }
  }



  Widget rowItem({required int index, bool showBorder = true}) {
    final HourlyHoroscope item = dataMap![index]!;
    return IntrinsicHeight(
      child: Container(
        decoration: BoxDecoration(
          border: showBorder
            ? Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
            : null
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Container(
              width: 125.w,
              decoration: BoxDecoration(
                border: Border(right: BorderSide(width: 1.w, color: ColorStyle.borderColor))
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(getTimePeriod(index)['name']??'-', style: TextStyle(fontSize: 30.sp, color: const Color.fromRGBO(198, 0, 0, 1)),),
                  SizedBox(height: 24.w),
                  CommonText(txt: getTimePeriod(index)['start']??'-', height: 1),
                  const CommonText(txt: '-', height: 1),
                  CommonText(txt: getTimePeriod(index)['end']??'-', height: 1),
                ],
              ),
            ),
            Expanded(
              child: Column(
                children: [
                  Container(
                    width: double.infinity,
                    height: 100.w,
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    alignment: Alignment.centerLeft,
                    decoration: BoxDecoration(
                      border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                    ),
                    child: CommonText(txt: item.timeConflict??'-'),
                  ),
                  Container(
                    width: double.infinity,
                    constraints: BoxConstraints(
                      minHeight: 100.w
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    alignment: Alignment.centerLeft,
                    decoration: BoxDecoration(
                      border: Border(bottom: BorderSide(width: 1.w, color: ColorStyle.borderColor))
                    ),
                    child: Row(
                      children: [
                        Image.asset('assets/icons/icon_yi.png', height: 40.w),
                        SizedBox(width: 10.w),
                        Expanded(child: CommonText(txt: item.suitableActivities?.join(' ') ?? '-'))
                      ],
                    ),
                  ),
                  Container(
                    width: double.infinity,
                    constraints: BoxConstraints(
                        minHeight: 100.w
                    ),
                    padding: EdgeInsets.symmetric(horizontal: 15.w),
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        Image.asset('assets/icons/icon_ji.png', height: 40.w),
                        SizedBox(width: 10.w),
                        Expanded(child: CommonText(txt: item.unsuitableActivities?.join(' ') ?? '-'))
                      ],
                    ),
                  )
                ],
              )
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommonHeader.appBar(context: context),
      backgroundColor: ColorStyle.pageDefaultColor,
      body: ListView(
        padding: EdgeInsets.fromLTRB(Constant.PAGEPADDING.w, 20.w, Constant.PAGEPADDING.w, 40.w),
        children: [
          const CommonTitleWidget(txt: '择吉时'),
          Container(
            padding: EdgeInsets.all(40.w),
            margin: EdgeInsets.only(top: 20.w),
            decoration: BoxDecoration(
              color: ColorStyle.themeLightColor,
              border: Border.all(width: 5.w, color: ColorStyle.borderColor),
              borderRadius: BorderRadius.all(Radius.circular(60.w))
            ),
            child: Column(
              children: [
                CommonShadowTextWidget(txt: dateShowText),
                Container(
                  margin: EdgeInsets.only(top: 20.w),
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.w, color: ColorStyle.borderColor)
                  ),
                  child: Column(
                    children: (dataMap != null && dataMap!.isNotEmpty) ? dataMap!.keys.map((key) {
                      return rowItem(index: key, showBorder: key < dataMap!.length - 1);
                    }).toList() : []
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
